const jwt = require('jsonwebtoken')
const { PUBLIC_KEY, PRIVATE_KEY } = require('../config/secret')
const { UNAUTHORIZATION, NAME_OR_PASSWORD_FAILED } = require('../config/error')
class LoginController {
	sign(ctx, next) {
		try {
			// 1.获取用户信息
			const { id, name } = ctx.user
			console.log(ctx.user)
			// 2.颁发令牌
			const token = jwt.sign({ id, name }, PRIVATE_KEY, {
				expiresIn: 24 * 60 * 60 * 7,
				algorithm: 'RS256'
			})
			// 3.返回用户信息
			ctx.body = {
				code: 0,
				message: '用户登陆成功',
				data: { token, id, name }
			}
		} catch (error) {
			console.log(error)
			ctx.app.emit('error', NAME_OR_PASSWORD_FAILED, ctx)
		}
	}

	test(ctx, next) {
		ctx.body = `验证身份通过`
	}
}

module.exports = new LoginController()
